import React, { cloneElement, useCallback, useEffect } from 'react'
import {
  bool,
  array,
  string,
  func
} from 'prop-types'

import { TabBarWrapper, TabBarListWrapper } from './styledTabbar'

import { useHistory } from 'react-router-dom'

export default function TabBar({
  fixed,
  children,
  activeColor,
  inactiveColor,
  selectedIndex,
  setSelectedIndex,
  border,
  route
}) {
  const history = useHistory()

  useEffect(() => {
    if (route) {
      history.listen((route) => {
        // 改变tabbar的index, 或者是name, 实现高亮
        setSelectedIndex(route.pathname.slice(1))
      })
    }
  }, [history, setSelectedIndex, route])

  const handleItemClick = useCallback((to, name) => {
    return () => {
      if (route) {
        // 切换路由
        history.push(to)
      } else {
        // 改变tabbar的index, 或者是name, 实现高亮
        setSelectedIndex(name)
      }
    }
  }, [history, route, setSelectedIndex])

  return (
    <TabBarWrapper
      fixed={fixed}
    >
      <TabBarListWrapper
        border={border}
        borderWidth={'1px 0 0 0'}
      >
        {
          React.Children.map(children, (child) => {
            return (
              // 实现element复制，可以同时将额外的属性传递给克隆返回的element
              cloneElement(
                child,
                {
                  activeColor,
                  inactiveColor,
                  selectedIndex,
                  handleItemClick
                }
              )
            )
          })
        }
      </TabBarListWrapper>
    </TabBarWrapper>
  )
}

// 定义组件属性(props)的默认值
TabBar.defaultProps = {
  fixed: true,
  route: false
}

// 定义组件属性（props）的类型
TabBar.propTypes = {
  fixed: bool,
  children: array.isRequired,
  activeColor: string,
  inactiveColor: string,
  selectedIndex: string,
  border: bool,
  setSelectedIndex: func,
  route: bool
}